# -*- coding: utf-8 -*-
import hashlib
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)


_GATEWAY = 'https://api.paytech88.com/payway/index'

APP_CONF = {
    '681618606': {
        'API_KEY': '50E5A011E38FABE0E0B5FD8BB8627567'
    },
}

def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_charge_sign(parameter, key):
    '''  生成下单签名 '''
    s = 'input_charset={}&appkey={}&out_trade_no={}&total_fee={}&notify_url={}&key={}'.format(
        parameter['input_charset'], parameter['appkey'], parameter['out_trade_no'],
        parameter['total_fee'], parameter['notify_url'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    _LOGGER.info(u'origin string: %s, sign:%s', s, sign)
    return sign


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    charge_resp = {}
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('appkey', app_id),
        ('input_charset', 'UTF-8'),
        ('sign_type', 'MD5'),
        ('total_fee', pay_amount),
        ('trade_time', local_now().strftime('%Y-%m-%d %H:%M:%S')),
        ('out_trade_no', pay.id),
        ('front_mer_url', '{}/pay/api/{}/paytech/'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH)),
        ('notify_url', '{}/pay/api/{}/paytech/'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH)),
    ))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    parameter_dict['sign'] = generate_charge_sign(parameter_dict, api_key)
    response = requests.post(_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    if response.status_code == 200:
        # response text is a pure html text
        cache_id = redis_cache.save_html(pay.id, response.text)
        charge_resp.update({
            'charge_info': settings.PAY_CACHE_URL + cache_id,
        })
        _LOGGER.info("paytech data after charge: %s", response.text)
    else:
        _LOGGER.warn('paytech data error, status_code: %s', response.status_code)
    return charge_resp


def verify_notify_sign(parameter, key):
    '''验证通知签名 '''
    s = 'appkey={}&out_trade_no={}&trade_no={}&success_time={}&trade_status={}&result_code={}&key={}'.format(
        parameter['appkey'], parameter['out_trade_no'], parameter['trade_no'],
        parameter['success_time'], parameter['trade_status'], parameter['result_code'],
        key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    calculated_sign = m.hexdigest().upper()
    sign = parameter['sign']
    if sign != calculated_sign:
        _LOGGER.info("paytech sign: %s, calculated sign: %", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % parameter)
    return sign


def check_notify_sign(request):
    data = request.POST
    _LOGGER.info("paytech notify data: %s", data)
    app_id = data['appkey']
    api_key = _get_api_key(app_id)
    verify_notify_sign(data, api_key)
    pay_id = data['out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('paytech event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    trade_status = int(data['trade_status'])
    mch_id = pay.mch_id
    trade_no = data['trade_no']
    total_fee = float(data['total_fee'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 1:
        _LOGGER.info('paytech check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pass
